#include "stdio.h"
#include "main.h"
#include "rs485.h"

#define BUFFER_SIZE           (16)
#define RS485_RX()            HAL_GPIO_WritePin(RS485_RE_GPIO_Port, RS485_RE_Pin, GPIO_PIN_RESET)
#define RS485_TX()            HAL_GPIO_WritePin(RS485_RE_GPIO_Port, RS485_RE_Pin, GPIO_PIN_SET)
#define GET_INDEX(x)          ((x) & (BUFFER_SIZE - 1))
#define GET_LEN(r, w)         ((w) - (r))

extern UART_HandleTypeDef huart2;

static uint8_t rx_buffer[BUFFER_SIZE];
static uint32_t rd_index = 0;
static volatile uint32_t wr_index = 0;

static int set_ec_mode()
{
  uint8_t tx_buffer[] = { 0xFE, 0x06, 0x00, 0x03, 0x00, 0x00, 0x6D, 0xC5 };
  uint32_t tick_start = HAL_GetTick();
  int check_over = 0;
  
  RS485_TX();
  HAL_UART_Transmit(&huart2, tx_buffer, sizeof(tx_buffer) / sizeof(tx_buffer[0]), 100);
  RS485_RX();
  
  while ((HAL_GetTick() - tick_start) < 100)
  {
#if 0
    {
      int i = 0;
      printf("R(%d): ", rd_index);
      for (i = rd_index; i != wr_index;i ++) {
        printf("%02x ", rx_buffer[GET_INDEX(i)]);
      }
      printf("\n");
    }
#endif
    if (GET_LEN(rd_index, wr_index) < 8) {
      continue;
    }
    if (rx_buffer[GET_INDEX(rd_index)] != 0xFE || rx_buffer[GET_INDEX(rd_index + 1)] != 0x06) {
      rd_index ++;
      continue;
    }
    check_over = 1;
    break;
  }
  rd_index = wr_index;
  
  return check_over ? 0 : -1;
}

int ec_sensor_init()
{
  HAL_UART_Receive_IT(&huart2, &rx_buffer[GET_INDEX(wr_index)], 1);
  
  return set_ec_mode();
}

int get_ec_sensor_value(int *temp_data, int *ec_data)
{
  uint8_t tx_buffer[] = { 0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC4, 0x0B };
  uint32_t tick_start = HAL_GetTick();
  int check_over = 0;
  
  RS485_TX();
  HAL_UART_Transmit(&huart2, tx_buffer, sizeof(tx_buffer) / sizeof(tx_buffer[0]), 500);
  RS485_RX();

  while ((HAL_GetTick() - tick_start) < 100) {
#if 0
    {
      int i = 0;
      printf("R(%d): ", rd_index);
      for (i = rd_index; i != wr_index;i ++) {
        printf("%02x ", rx_buffer[GET_INDEX(i)]);
      }
      printf("\n");
    }
#endif
    if (GET_LEN(rd_index, wr_index) < 9) {
      continue;
    }
    if (rx_buffer[GET_INDEX(rd_index)] != 0x01 || 
      rx_buffer[GET_INDEX(rd_index + 1)] != 0x03 || 
      rx_buffer[GET_INDEX(rd_index + 2)] != 0x04) {
      rd_index ++;
      continue;
    }
    *temp_data = ((rx_buffer[GET_INDEX(rd_index + 3)] << 8) | (rx_buffer[GET_INDEX(rd_index + 4)])) / 10;
    *ec_data = (rx_buffer[GET_INDEX(rd_index + 5)] << 8) | (rx_buffer[GET_INDEX(rd_index + 6)]);
    check_over = 1;
    break;
  }
  rd_index = wr_index;
  
  return check_over ? 0 : -1;
}

// 01 03 04 00 4E 01 03 DB B5
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
  if (huart == &huart2)
  {
    HAL_UART_Receive_IT(&huart2, &rx_buffer[GET_INDEX(++wr_index)], 1);
  }
}
